package com.ajie.service.impl;

import com.ajie.entity.New;
import com.ajie.mapper.NewMapper;
import com.ajie.service.NewService;
import com.ajie.utils.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class NewServiceImpl implements NewService {


    @Autowired
    private NewMapper newsMapper;
    
    @Autowired
    private RedisUtil redisUtil;
    
    @Autowired
    JedisUtils jedisUtils ;
    
    @Autowired
    TokenUtil tokenUtil;
    
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    
    
    @Override
    public Result findPage(@RequestBody QueryInfo queryInfo, String header) {
        
        log.info("该文件名是：NewServiceImpl,该方法是：findPage");
        log.info("1.开始新闻咨询数据分页-->页码{}, -->页数{}, -->查询内容{}",queryInfo.getPageNumber(),queryInfo.getPageSize(),queryInfo.getQueryString());
        List<New> result = newsMapper.findPage(queryInfo.getQueryString());
        result.forEach(new1->{
            Long lookNum = jedisUtils.zscore("looks","new::"+new1.getId()).longValue();
            Long likeNum = jedisUtils.zscore("likes","new::"+new1.getId()).longValue();
            Long favouriteNum = jedisUtils.zscore("favourites","new::"+new1.getId()).longValue();
            new1.setLookNum(lookNum);
            new1.setLikeNum(likeNum);
            new1.setFavouriteNum(favouriteNum);
            boolean b = false;
            boolean b1 = false;
            boolean b2 = false;
            if (header != null){
                Set<Object> set = redisUtil.sGet("newId::"+ new1.getId().toString());
                //如果非空，遍、
                    for (Object item2 : set){
                        String[] split = item2.toString().split("::");
                        String uid = split[2];
                        if (SecurityUtil.getUserId().toString().equals(uid)){
                            if ("look".equals(split[0])){
                                b = true;
                            }
                            if ("like".equals(split[0])){
                                b1 = true;
                            }
                            if ("favourite".equals(split[0])){
                                b2 = true;
                            }
                        }
                    }
            }
            new1.setLook(b);
            new1.setLike(b1);
            new1.setFavourite(b2);
          
        });
        result.sort(Comparator.comparing(New::getCreateTime).reversed());
        //4.把list进行分页
        Page page = new Page(queryInfo.getPageNumber(),queryInfo.getPageSize());
        // 获取list的大小
        int total = result.size();
        
        page.setTotal(total);
        int startIndex = (queryInfo.getPageNumber()-1) * queryInfo.getPageSize();
        int endIndex = Math.min(startIndex+queryInfo.getPageSize(),total);
        if (startIndex< total){
            page.addAll(result.subList(startIndex,endIndex));
        }
        
        PageInfo<Object> objectPageInfo = new PageInfo<>(page);
        log.info("查询的总条数是-->{}",total);
        log.info("分页列表-->{}",objectPageInfo.getList());
        return new PageResult(total, objectPageInfo.getList());
    }

    @Override
    public Result insert(New news) {
        log.info("该文件名是：NewServiceImpl,该方法是：insert");
        newsMapper.insert(news);
        redisUtil.zAdd("looks", "new::" + news.getId().toString(), 0);
        redisUtil.zAdd("likes","new::" + news.getId().toString(),0);
        redisUtil.zAdd("favourites","new::" + news.getId().toString(),0);
        redisUtil.delKey("userInfo_"+ SecurityUtil.getUsername());
        return Result.success("添加新闻咨询数据成功");
    }

    @Override
    public Result delete(Long id) {
        log.info("该文件名是：NewServiceImpl,该方法是：delete");
        newsMapper.delete(id);
        redisUtil.delKey("userInfo_"+ SecurityUtil.getUsername());
        return Result.success("删除新闻咨询数据成功");
    }

    @Override
    public Result update(New news) {
        log.info("该文件名是：NewServiceImpl,该方法是：update");
        newsMapper.update(news);
        // redisUtil.delKey("userInfo_"+ SecurityUtil.getUsername());
        return Result.success("修改新闻咨询数据成功");
    }
    
    @Override
    public List<New> getAll() {
        
        return newsMapper.getAll();
    }
    
    @Override
    public Result findPageCheck(QueryInfo queryInfo, String header) {
    
        log.info("该文件名是：NewServiceImpl,该方法是：findPageCheck");
        log.info("1.开始新闻咨询数据分页-->页码{}, -->页数{}, -->查询内容{}",queryInfo.getPageNumber(),queryInfo.getPageSize(),queryInfo.getQueryString());
        PageHelper.startPage(queryInfo.getPageNumber(),queryInfo.getPageSize());
        Page<New> page = newsMapper.findPageCheck(queryInfo.getQueryString());
        long total = page.getTotal();
        List<New> result = page.getResult();
        log.info("查询的总条数是-->{}",total);
        log.info("分页列表-->{}",result);
        return new PageResult(total, result);
    }
    
    @Override
    public Result updateStatus(Long id) {
        newsMapper.updateStatus(id);
        return Result.success("审核完成");
    }
    
    
}
